<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
      <el-form-item label="供应商名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入供应商名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="id主键" align="center" prop="id" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="name" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="电话" align="center" prop="phone" />
      <!-- <el-table-column label="数组" align="center" prop="infos" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template v-slot="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAddress(scope.row)">修改地址</el-button> -->
          <el-button size="mini" type="text" @click="toCommodity(scope.row)">查看商品</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改地址 -->
    <el-dialog :title="title" :visible.sync="openaddress" width="35%" v-dialogDrag append-to-body>
      <div>
        <el-button type="primary" plain @click="addressShow = true">新增</el-button>
        <div class="addressstyle" v-for="item,index in addressList" :key="index+'b'">
          <p style="white-space: nowrap;">{{item.name}} / {{ returnstr(item.city)}} / {{item.address}}</p>
          <div>
              <el-button type="primary" plain @click="openEdit(item,index)">编辑</el-button>
            <el-button type="danger" plain @click="addressList.splice(index,1)">删除</el-button>
          </div>
          
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormaddress">确 定</el-button>
        <el-button @click="openaddress = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改地址 -->
    <el-dialog :title="title" :visible.sync="addressShow" width="35%" v-dialogDrag append-to-body>
        <el-form ref="addressform" :model="addressFfom" :rules="rulesaddress" label-width="80px">
          <el-form-item label="店名" prop="name">
            <el-input v-model="addressFfom.name" @input="nameInput" placeholder="请输入店名" />
          </el-form-item>
          <el-form-item label="省市区" prop="city">
            <el-cascader
              v-model="addressFfom.city"
              :options="cityList" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="详情地址" prop="address">
            <el-input v-model="addressFfom.address" placeholder="请输入详情地址" />
          </el-form-item>
          <el-form-item label="时间" prop="oldtimes">
            <el-cascader
            collapse-tags
              v-model="addressFfom.oldtimes"
              :options="timeList" clearable
              :props="{ multiple: true }"></el-cascader>
            <!-- <el-cascader-panel v-model="addressFfom.times" :options="timeList" :props="{ multiple: true }"></el-cascader-panel> -->
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitaddress">确 定</el-button>
        <el-button @click="addressShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createSupplier, updateSupplier, deleteSupplier, getSupplier, getSupplierPage, exportSupplierExcel } from "@/api/qd/supplier";
import { isNumber } from 'min-dash';

export default {
  name: "Supplier",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序-供应商列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        name: null,
        nickName: null,
        phone: null,
        infos: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      addressShow:false,
      cityList:[],
      timeList:[],
      addressFfom:{},
      rulesaddress:{
        name:[{ required: true, message: '请输入店名', trigger: 'blur' }],
        city:[{ required: true, message: '请选择省市区', trigger: 'change' }],
        address:[{ required: true, message: '请输入详情地址', trigger: 'blur' }],
        oldtimes:[{ required: true, message: '请选择时间', trigger: 'change' }]
      },
      rowobj:{},
      addressList:[],
      openaddress:false,
      isedit:null
    };
  },
  created() {
    this.getList();
    this.getotherData()
  },
  methods: {
    toCommodity(row){  // 前往商品
      this.$router.push({path:'/miniProgramData/commodityIndex',query:{supplierId:row.id}})
    },
    submitFormaddress(){
      this.addressList.forEach(itemm=>{
        itemm.city=itemm.city.join('-')
        itemm.times = []
        itemm.oldtimes.forEach(item=>{
        const a = itemm.times.some((ite,inde)=>{
          if(ite.name === item[0]){
                itemm.times[inde].time.push(item[1])
                return true
              }
            })
            if(!a) itemm.times.push({name:item[0],time:[item[1]]})
          })
        })
      updateSupplier({...this.rowobj,infos:this.addressList}).then(res=>{
        this.$message.success('修改成功')
        this.openaddress = false
      })
    },
    openEdit(row,index){
      this.addressFfom = {...row}
      this.isedit = index
      this.addressShow = true
    },
    submitaddress(){  // 修改地址确认
        this.$refs.addressform.validate((valid) => {
          if (valid) {
            if(isNumber(this.isedit)){
              this.$set(this.addressList,this.isedit,this.addressFfom)
              this.addressFfom = {}
              this.isedit = null
            }else{
              this.addressList.push(this.addressFfom)
              this.addressFfom = {}
            }
            this.addressShow= false
          }
        });
        
    },
    returnstr(str){
      if(typeof str !== 'object')return ''
      return str.join('-')
    },
    nameInput(e,index){  // 名称input事件
      this.addressList.some((item,inde)=>{
        if(item.name === e){
          this.$set(this.addressFfom,'name','')
          return this.$message.warning('店名不能重复')
        }
      })
    },
    handleAddress(row){   // 打开修改地址弹窗
      getSupplier(row.id).then(res=>{
        this.addressList = res.data.infos ?? []
        this.addressList.forEach(item=>{
          if(item.city) item.city=item.city.split('-')
          item.oldtimes = []
          if(item.times instanceof Array){
            item.times.forEach(ite=>{
              ite.time.forEach(it=>{
                item.oldtimes.push([ite.name,it])
              })
            })
          }
          
        })
        this.openaddress=true
        this.rowobj = res.data
      })
      
    },
    getotherData(){
      // 获取时间
      this.$axios({url:'/qd/supplier/getWeekTimes',method:'get'}).then(res=>{
        
        this.timeList = res.data ?? []
        this.timeList.forEach(item=>{
          item.value = item.name
          item.label = item.name
          item.children = []
          item.time.forEach(ite=>{
            item.children.push({value:ite,label:ite})
          })
        })
      })
      // 获取获取省市区
      this.$axios({url:'/qd/supplier/getTree',method:'get'}).then(res=>{
        this.cityList = res.data ?? []
        this.cityList.forEach(item=>{
          item.value = item.label
          item.children.forEach(ite=>{
            ite.value = ite.label
            ite.children.forEach(it=>{
              it.children = null
              it.value = it.label
            })
          })
        })
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getSupplierPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        nickName: undefined,
        phone: undefined,
        infos: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小程序-供应商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSupplier(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小程序-供应商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateSupplier(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSupplier(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除小程序-供应商编号为"' + id + '"的数据项?').then(function() {
          return deleteSupplier(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有小程序-供应商数据项?').then(() => {
          this.exportLoading = true;
          return exportSupplierExcel(params);
        }).then(response => {
          this.$download.excel(response, '小程序-供应商.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped lang="scss">
.addressstyle{
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: #bbb 1px solid;
  padding: 10px;
  p{
    margin-right: 5px;
  }
}
</style>